package com.ytclub.subject.domain.service.impl;

import com.alibaba.fastjson.JSON;
import com.ytclub.subject.common.enums.IsDeletedFlagEnum;
import com.ytclub.subject.domain.convert.SubjectCategoryConverter;
import com.ytclub.subject.domain.entity.SubjectCategoryBO;
import com.ytclub.subject.domain.entity.SubjectLabelBO;
import com.ytclub.subject.domain.service.SubjectCategoryDoaminService;
import com.ytclub.subject.domain.util.CacheUtil;
import com.ytclub.subject.infra.basic.entity.SubjectCategory;
import com.ytclub.subject.infra.basic.entity.SubjectLabel;
import com.ytclub.subject.infra.basic.entity.SubjectMapping;
import com.ytclub.subject.infra.basic.service.SubjectCategoryService;
import com.ytclub.subject.infra.basic.service.SubjectLabelService;
import com.ytclub.subject.infra.basic.service.SubjectMappingService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

/**
 * @author: HuangQi
 * @date: Created in 21:14 2023/12/14
 * @description:
 */
@Service
@Slf4j
public class SubjectCategoryDoaminServiceImpl implements SubjectCategoryDoaminService {

    @Resource
    private SubjectCategoryService subjectCategoryService;

    @Resource
    private SubjectMappingService subjectMappingService;

    @Resource
    private SubjectLabelService subjectLabelService;

    @Resource(name = "labelThreadPool")
    private ThreadPoolExecutor labelThreadPool;

    @Resource
    private CacheUtil cacheUtil;


    /**
     * 新增分类
     *
     * @param subjectCategoryBO 新增分类的信息
     * @return 新增结果
     */
    @Override
    public Boolean add(SubjectCategoryBO subjectCategoryBO) {
        if (log.isInfoEnabled()) {
            log.info("SubjectCategoryDoaminServiceImpl.add.bo:{}", JSON.toJSONString(subjectCategoryBO));
        }

        // 参数转换
        SubjectCategory subjectCategory =
                SubjectCategoryConverter.INSTANCE.convertBoToCategory(subjectCategoryBO);
        subjectCategory.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());

        // 调用service
        int count = subjectCategoryService.insert(subjectCategory);
        return count > 0;
    }

    /**
     * 查询分类
     *
     * @param subjectCategoryBO 查询条件
     * @return 分类列表
     */
    @Override
    public List<SubjectCategoryBO> queryCategory(SubjectCategoryBO subjectCategoryBO) {
        if (log.isInfoEnabled()) {
            log.info("SubjectCategoryDoaminServiceImpl.queryCategory.bo:{}", JSON.toJSONString(subjectCategoryBO));
        }
        // 参数转换
        SubjectCategory subjectCategory =
                SubjectCategoryConverter.INSTANCE.convertBoToCategory(subjectCategoryBO);
        subjectCategory.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());

        // 调用service
        List<SubjectCategory> subjectCategoryList = subjectCategoryService.queryCategory(subjectCategory);
        List<SubjectCategoryBO> boList =
                SubjectCategoryConverter.INSTANCE.convertBoToCategory(subjectCategoryList);
        if (log.isInfoEnabled()) {
            log.info("SubjectCategoryDoaminServiceImpl.queryPrimaryCategory.boList:{}",
                    JSON.toJSONString(boList));
        }

        // 查询分类下的科目数量
        boList.forEach(bo -> {
            Integer subjectCount = subjectCategoryService.querySubjectCount(bo.getId());
            bo.setCount(subjectCount);
        });

        // 返回结果
        return boList;
    }

    /**
     * 更新分类
     *
     * @param subjectCategoryBO 更新的信息
     * @return 更新结果
     */
    @Override
    public Boolean update(SubjectCategoryBO subjectCategoryBO) {
        if (log.isInfoEnabled()) {
            log.info("SubjectCategoryDoaminServiceImpl.update.bo:{}", JSON.toJSONString(subjectCategoryBO));
        }

        // 调用service
        SubjectCategory subjectCategory =
                SubjectCategoryConverter.INSTANCE.convertBoToCategory(subjectCategoryBO);
        int count = subjectCategoryService.update(subjectCategory);
        return count > 0;
    }


    /**
     * 删除分类
     *
     * @param subjectCategoryBO 删除的id
     * @return 删除结果
     */
    @Override
    public Boolean delete(SubjectCategoryBO subjectCategoryBO) {
        if (log.isInfoEnabled()) {
            log.info("SubjectCategoryDoaminServiceImpl.delete.bo:{}", JSON.toJSONString(subjectCategoryBO));
        }

        // 调用service
        SubjectCategory subjectCategory =
                SubjectCategoryConverter.INSTANCE.convertBoToCategory(subjectCategoryBO);
        subjectCategory.setIsDeleted(IsDeletedFlagEnum.DELETED.getCode());
        int count = subjectCategoryService.update(subjectCategory);
        return count > 0;
    }

    /**
     * 查询分类及标签一次性
     *
     * @param subjectCategoryBO 分类信息
     * @return 分类及标签信息
     */
    @Override
    @SneakyThrows
    public List<SubjectCategoryBO> queryCategoryAndLabel(SubjectCategoryBO subjectCategoryBO) {
        if (log.isInfoEnabled()) {
            log.info("SubjectCategoryDoaminServiceImpl.queryCategoryAndLabel.bo:{}", JSON.toJSONString(subjectCategoryBO));
        }
        Long id = subjectCategoryBO.getId();
        String cacheKey = "CategoryAndLabel." + id;
        List<SubjectCategoryBO> categoryBOList = cacheUtil.getResult(cacheKey, SubjectCategoryBO.class,
                (key) -> getSubjectCategoryBOS(id));

        // 使用futureTask获取标签信息
        /*
        // 一次获取标签信息
        List<FutureTask<Map<Long, List<SubjectLabelBO>>>> futureTaskList = new LinkedList<>();
        // 线程池并发调用
        Map<Long, List<SubjectLabelBO>> map = new HashMap<>();
        // 提交任务,并执行
        categoryBOList.forEach(category -> {
            FutureTask<Map<Long, List<SubjectLabelBO>>> futureTask = new FutureTask<>(() ->
                    getLabelBOList(category)
            );
            futureTaskList.add(futureTask);
            labelThreadPool.submit(futureTask);
        });
        // 取得执行完成的结果,并合并到map集合中
        for (FutureTask<Map<Long, List<SubjectLabelBO>>> futureTask : futureTaskList) {
            try {
                Map<Long, List<SubjectLabelBO>> resultMap = resultMap = futureTask.get();
                if (!CollectionUtils.isEmpty(resultMap)) {
                    map.putAll(resultMap);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }*/

        // 返回结果
        return categoryBOList;
    }

    /**
     * 获取分类及标签信息
     *
     * @param categoryId 分类id
     * @return 分类及标签信息
     */
    private List<SubjectCategoryBO> getSubjectCategoryBOS(Long categoryId) {
        // 查询当前大类下所有分类
        SubjectCategory subjectCategory = new SubjectCategory();
        subjectCategory.setParentId(categoryId);
        subjectCategory.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
        List<SubjectCategory> subjectCategoryList = subjectCategoryService.queryCategory(subjectCategory);
        if (log.isInfoEnabled()) {
            log.info("SubjectCategoryDoaminServiceImpl.queryCategoryAndLabel.subjectCategoryList:{}", JSON.toJSONString(subjectCategoryList));
        }
        List<SubjectCategoryBO> categoryBOList = SubjectCategoryConverter.INSTANCE.convertBoToCategory(subjectCategoryList);

        // 使用CompletableFuture获取标签信息
        // 使用CompletableFuture提交任务并执行
        List<CompletableFuture<Map<Long, List<SubjectLabelBO>>>> completableFutureList = categoryBOList.stream().map(category ->
                CompletableFuture.supplyAsync(() -> getLabelBOList(category), labelThreadPool)
        ).collect(Collectors.toList());
        // 获取执行完成的结果,并合并到map集合中
        Map<Long, List<SubjectLabelBO>> map = new HashMap<>();
        completableFutureList.forEach(future -> {
            try {
                Map<Long, List<SubjectLabelBO>> resultMap = resultMap = future.get();
                if (!CollectionUtils.isEmpty(resultMap)) {
                    map.putAll(resultMap);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        });

        // 将LabelBOList信息放入对应的category中
        categoryBOList.forEach(categoryBO -> {
            categoryBO.setLabelBOList(map.get(categoryBO.getId()));
        });
        return categoryBOList;
    }

    /**
     * 根据category获取label信息
     *
     * @param category 分类信息
     * @return label信息
     */
    private Map<Long, List<SubjectLabelBO>> getLabelBOList(SubjectCategoryBO category) {
        Map<Long, List<SubjectLabelBO>> labelMap = new HashMap<>();
        // 从mapping表中获取labelIdList
        SubjectMapping subjectMapping = new SubjectMapping();
        subjectMapping.setCategoryId(category.getId());
        List<SubjectMapping> mappingList = subjectMappingService.queryLabelId(subjectMapping);
        if (CollectionUtils.isEmpty(mappingList)) {
            return null;
        }
        List<Long> labelIdList = mappingList.stream().map(SubjectMapping::getLabelId).collect(Collectors.toList());

        // 从label表中获取label信息
        List<SubjectLabel> labelList = subjectLabelService.batchQueryById(labelIdList);

        // 转换label信息 label -> labelBo
        List<SubjectLabelBO> labelBOList = new LinkedList<>();
        labelList.forEach(label -> {
            SubjectLabelBO labelBO = new SubjectLabelBO();
            labelBO.setId(label.getId());
            labelBO.setLabelName(label.getLabelName());
            labelBO.setCategoryId(label.getCategoryId());
            labelBO.setSortNum(label.getSortNum());
            labelBOList.add(labelBO);
        });
        labelMap.put(category.getId(), labelBOList);
        return labelMap;
    }
}
